package com.dragee.modules.sys.controller;

import com.dragee.common.PageUtils;
import com.dragee.common.R;
import com.dragee.config.exception.BusinessErrorType;
import com.dragee.config.exception.BusinessException;
import com.dragee.constants.AuthConstants;
import com.dragee.constants.CommonConstants;
import com.dragee.modules.sys.dao.SysUserRoleMapper;
import com.dragee.modules.sys.entity.UserEntity;
import com.dragee.modules.sys.service.ISysRoleService;
import com.dragee.modules.sys.service.UserRoleService;
import com.dragee.modules.sys.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 用户表
 *
 * @author tys
 * @email tys@mail.com
 * @date 2020-11-11 17:46:45
 */
@RestController
@RequestMapping("sys/user")
@Api(tags = "SYS - 用户管理")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ISysRoleService rolesService;
    @Autowired
    private UserRoleService userRoleService;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private JdbcTemplate jdbcTemplate;


    /**
     * 列表
     */
    @GetMapping("list")
    @ApiOperation("用户列表")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params, null);
        return R.ok().put("data", page);
    }

    @GetMapping("resetPwd")
    @ApiOperation("重置密码")
    public R resetPwd(Long userId){
        if (userId == null) {
            throw new BusinessException(BusinessErrorType.INVALID_PARAMS);
        }
        UserEntity user = userService.getById(userId);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }
        user.setPassword(new Sha256Hash(CommonConstants.initPassword, AuthConstants.SLAT_PWD).toHex());
        userService.saveOrUpdate(user);
        return R.ok();
    }



    @GetMapping("updatePwd")
    @ApiOperation("修改密码")
    public R updatePwd(Long userId, String pwd){
        UserEntity user = userService.getById(userId);
        user.setPassword(pwd);
        userService.saveOrUpdate(user);
        return R.ok();
    }

    /**
     * 删除
     */
    @GetMapping("change-status")
    @ApiOperation("切换状态")
    public R changeStatus(String status, String userId){
        UserEntity user = userService.getById(Long.parseLong(userId));
        user.setStatus(status);
        userService.saveOrUpdate(user);
        return R.ok();
    }





}
